package com.hdoit.kylin.web.user.provider;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.PageContext;

import org.springframework.util.StringUtils;

import com.hdoit.kylin.logical.user.model.Teacher;
import com.hdoit.kylin.logical.user.service.IStudentService;
import com.hdoit.kylin.logical.user.service.ITeacherService;
import com.hdoit.kylin.web.user.modelconfig.TeacherConfig;
import com.tennetcn.common.aop.CommonApplicationContextUtil;
import com.tennetcn.common.message.ListItem;
import com.tennetcn.common.utils.CookieUtils;
import com.tennetcn.component.attribute.provider.ISingleOptionListProvider;
import com.tennetcn.component.web.SessionWebFactory;
import com.tennetcn.plugins.devshorts.enumerable.Enumerable;

public class TeacherProvider implements ISingleOptionListProvider<ListItem>{
	private String source;
	private List<ListItem> dataList;
	
	public TeacherProvider(){
		
	};
	
	public TeacherProvider(String source) {
		this.source=source;
	}

	@Override
	public List<ListItem> getDataList(Object viewData) {
		SessionWebFactory sessionWebFactory=CommonApplicationContextUtil.getCurrentContext().getBean(SessionWebFactory.class);
		ITeacherService teacherService=CommonApplicationContextUtil.getCurrentContext().getBean(ITeacherService.class);
		IStudentService studentService=CommonApplicationContextUtil.getCurrentContext().getBean(IStudentService.class);
		String loginId=sessionWebFactory.getCurrentLogin().getLoginId();
		
		String groupId=teacherService.queryGroupIdByLoginId(loginId);
		if(StringUtils.isEmpty(groupId))
			groupId=studentService.queryGroupIdByLoginId(loginId);
		
		List<Teacher> teachers=teacherService.queryListByGroupId(null, null, groupId);
		
		if(null==teachers||0>=teachers.size())
			return null;
		
		dataList=new ArrayList<ListItem>();
		ListItem listItem;
		for(Teacher teacher:teachers){
			listItem=new ListItem(teacher.getTeacherName(), teacher.getEmployeeId());
			dataList.add(listItem);
		}
		
		return dataList;
	}

	@Override
	public ListItem getSelectedItem(Object value, Object viewData) {
		if(null==dataList||0>=dataList.size())
			return null;
		
		if(StringUtils.isEmpty(value)){
			if(TeacherConfig.class.getName().equals(source)){
				try{
					PageContext pageContext=(PageContext)viewData;
					HttpServletRequest httpRequest=(HttpServletRequest)pageContext.getRequest();
					value=CookieUtils.getCookieValue(httpRequest,"checkId",true);
				}
				catch(Exception e){
					return null;
				}
			}
		}
		
		if(StringUtils.isEmpty(value))
			return null;
		
		final String teacherId=value.toString();
		return Enumerable.init(dataList).filter(d->teacherId.equals(d.getValue())).first();
	}

}
